#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include "msglog.h"
#include "systime.h"

#define MAX_OUTPNT_BUF 255

static bool enable_log = true;

void msg_log(const char* fmt,...)
{
	/* Build base information */
	static char outbuf[MAX_OUTPNT_BUF+3];
	int len, wlen, olen;
	va_list(vafmt);

	if (!enable_log) return; // stop output infomation

	/* Log time */
	snprintf(outbuf, MAX_OUTPNT_BUF, 
		"%8d ", GetTickCount());
	
	/* output format info to out buffer */
	len = strlen(outbuf);
	wlen = len;
	
	va_start(vafmt, fmt);
	olen = vsnprintf(outbuf+len, MAX_OUTPNT_BUF-len, fmt, vafmt);
	wlen += olen;
	if (wlen > 0 && wlen <= MAX_OUTPNT_BUF){
		/* write line terminaler */
		outbuf[wlen]='\r';
		outbuf[wlen+1]='\n';
		outbuf[wlen+2]='\0';
	}else if (wlen < 0){
		/* user out data too long */
		outbuf[MAX_OUTPNT_BUF-6] = '.';
		outbuf[MAX_OUTPNT_BUF-5] = '.';
		outbuf[MAX_OUTPNT_BUF-4] = '.';
		outbuf[MAX_OUTPNT_BUF-3] = '\r';
		outbuf[MAX_OUTPNT_BUF-2] = '\n';
		outbuf[MAX_OUTPNT_BUF-1] = '\0';
	}
	va_end(vafmt);

	printf("%s", outbuf);

}

void msg_log_set_status(bool enable)
{
	enable_log = enable;	
}

bool msg_log_status(void){
	return enable_log;
}

